package com.msb.mall.ware.service.impl;

import com.msb.common.constant.WareConstant;
import com.msb.mall.ware.entity.PurchaseDetailEntity;
import com.msb.mall.ware.service.PurchaseDetailService;
import com.msb.mall.ware.service.WareSkuService;
import com.msb.mall.ware.vo.PurchaseDoneVO;
import com.msb.mall.ware.vo.PurchaseItemDoneVO;
import com.msb.mall.ware.vo.PurchaseMergeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.ware.dao.PurchaseDao;
import com.msb.mall.ware.entity.PurchaseEntity;
import com.msb.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 合并整单 - 获取采购单  状态为 新建/已分配
     *
     * @return
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 采购需求合并为 采购单
     *
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public int merge(PurchaseMergeVO vo) {
        Long purchaseId = vo.getPurchaseId();
        // 根据是否选取合并的采购单分为两种情况---新建采购单/已有采购单
        if (null == purchaseId){
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.purchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            // 采购单id
            purchaseId = purchaseEntity.getId();
        }

        PurchaseEntity pur = this.getById(purchaseId);
        if (pur.getStatus() > WareConstant.purchaseStatusEnum.ASSIGED.getCode()){
            return -1;
        }

        // 合并采购需求
        List<Long> items = vo.getItems();
        List<PurchaseDetailEntity> purDetailList = purchaseDetailService.listByIds(items);
        Boolean flag = true;
        for (PurchaseDetailEntity item : purDetailList) {
            if (item.getStatus() != WareConstant.purchaseDetailStatusEnum.CREATED.getCode()){
                flag = false;
                break;
            }
        }

        if (!flag){
            return -1;
        }

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purList = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.purchaseDetailStatusEnum.ASSIGED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purList);

        // 更新采购单更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

        return 1;
    }

    /**
     * 领取采购单
     *
     * @param ids
     */
    @Override
    public int receivePurchase(List<Long> ids) {
        // 获取要领取的采购单，只能领取新建/已分配状态的采购单
        List<PurchaseEntity> purList = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            return (item.getStatus() == WareConstant.purchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.purchaseStatusEnum.ASSIGED.getCode()
            );
        }).map(item -> {
            item.setStatus(WareConstant.purchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());
        if (null == purList || purList.size() == 0){
            return -1;
        }
        // 修改采购单状态为已领取
        this.updateBatchById(purList);
        // 修改关联的采购需求的状态为正在采购
        ids.forEach(id -> {
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(item -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setStatus(WareConstant.purchaseDetailStatusEnum.BUYING.getCode());
                detailEntity.setId(item.getId());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        });
        return 1;
    }

    /**
     * 完成采购
     * 成功-入库  失败-原因
     * @param vo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {
        // 改变每个采购需求的状态
        // 记录采购的状态 默认：完成
        Boolean flag = true;
        List<PurchaseDetailEntity> purDetailList = new ArrayList<>();
        List<PurchaseItemDoneVO> items = vo.getItems();
        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            Integer status = item.getStatus();
            if (status == WareConstant.purchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.purchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.purchaseDetailStatusEnum.FINISH.getCode());
                // 采购成功-入库
                PurchaseDetailEntity pde = purchaseDetailService.getById(item.getItemId());
                wareSkuService.toStock(pde.getSkuId(),pde.getWareId(),pde.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            purDetailList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purDetailList);

        // 改变采购单状态
        Long id = vo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.purchaseStatusEnum.FINISH.getCode()
                :WareConstant.purchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);

    }

}